const IP2Region = require('ip2region').default;
// 创建一个IP2Region实例
const query = new IP2Region();


/**
 * @name getClientIpCity
 * @description 获取客户端定位
 * @param {string} ip - 需要确定的ip
 * @return {$ObjMap} {"country":"","province":"","city":"内网IP","isp":"内网IP"}
 * */
exports.getClientIpCity = (ip) => {
    const ipAddress = query.search(ip);
    // 打印查询结果1
    console.log('>>> ipAddress: ', ipAddress)
}

exports.randomMath = (min,max) => {
    return Math.round(Math.random()*(max-min) + min)
}
/**
 * @name isUrl
 * @description 判断是否是一个在线外链图片
 * @param {string} url 需要检测的图片链接
*/
exports.isUrl = (url) =>  {
    const regex = /\b(https?):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/i;
    return regex.test(url);
}


/**
 * @method 获取客户端IP地址
 * @param {string} req 传入请求HttpRequest
 * 客户请求的IP地址存在于request对象当中
 * express框架可以直接通过 req.ip 获取
 */
exports.getClientIp = function (req) {
    return req.headers['x-forwarded-for'] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress ||
        '';
}

// 上述代码是直接获取的IPV4地址，如果获取到的是IPV6，则通过字符串的截取来转换为IPV4地址。
exports.ipv6ToV4 =  function (ip) {
    if(ip.split(',').length>0){
        ip = ip.split(',')[0]
    }
    ip = ip.substr(ip.lastIndexOf(':')+1,ip.length);
    return ip
}

